<template>
  <div>
    <BasicTable @register="registerTable">
      <!-- 表格工具栏按钮-->
      <template #toolbar>
        <a-button type="primary" @click="openEdit(false)"> 新增部门 </a-button>
      </template>

      <!-- 行操作按钮 -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <div class="flex justify-center">
            <TableAction
              :actions="[
                {
                  icon: 'clarity:note-edit-line',
                  tooltip: '编辑',
                  onClick: openEdit.bind(null, true, record),
                },
                {
                  icon: 'ant-design:delete-outlined',
                  color: 'error',
                  tooltip: '删除',
                  popConfirm: {
                    title: '是否确认删除',
                    placement: 'left',
                    confirm: handleDelete.bind(null, record),
                  },
                },
              ]"
            />
          </div>
        </template>
      </template>
    </BasicTable>

    <!-- 新增/编辑 窗口-->
    <DeptEdit ref="editRef" @success="reload" />
  </div>
</template>
<script lang="ts" setup>
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    FormSchema,
    SwitchRender,
    TagRender,
    DeletedTagRender,
  } from '@/components/Table';

  import DeptEdit from './DeptEdit.vue';
  import { ref } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { update, deleteById, pager } from '@/api/user/dept';
  import { formatToDateTime } from '@/utils/dateUtil';

  // 自定义组件名称, 默认为文件名
  defineOptions({ name: 'Dept' });

  const { createMessage } = useMessage();

  // 搜索面板
  const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '部门名称',
      component: 'Input',
      colProps: { span: 6 },
    },
    {
      field: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        options: [
          { label: '启用', value: 1 },
          { label: '停用', value: 0 },
        ],
      },
      colProps: { span: 6 },
    },
  ];

  // 表格列: width 如果是数字类型, 则是按比例展示, fixed 会失效
  const columns: BasicColumn[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: '8rem',
      fixed: 'left',
    },
    {
      title: '部门名称',
      dataIndex: 'name',
      width: '15rem',
    },
    {
      title: '负责人',
      dataIndex: 'manager',
      width: '10rem',
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      width: '10rem',
    },

    {
      title: '创建人',
      dataIndex: 'creator',
      width: '10rem',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: '10rem',
      format: (text) => formatToDateTime(text),
    },

    {
      title: '是否删除',
      dataIndex: 'deleted',
      width: '5rem',
      customRender: ({ record }) => DeletedTagRender(record.deleted),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: '8rem',
      customRender: ({ record }) =>
        SwitchRender({
          value: record.status,
          onchange: (checked) => updateStatus(record, checked),
        }),
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '12rem',
      fixed: 'right',
      align: 'center',
    },
  ];

  // 编辑窗口
  const editRef = ref<any>({});

  // 注册表格
  const [registerTable, { reload }] = useTable({
    title: '部门列表',
    api: pager,
    columns,
    // 搜索框配置: 是否打开搜索框、搜索框配置
    useSearchForm: true,
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
    },
    // 表格配置:
    showTableSetting: true, // 是否显示设置按钮
    bordered: true, // 是否包含边框
    showIndexColumn: false, // 是否包含索引列
  });

  // 打开编辑窗口
  function openEdit(isUpdate: boolean, record?: Recordable) {
    editRef.value.open(isUpdate, record);
  }

  // 删除
  async function handleDelete(record: Recordable) {
    await deleteById(record.id);
    await reload();
  }

  // 更新状态
  async function updateStatus(record: any, checked: any) {
    record.pendingStatus = true;
    const newStatus = checked ? 1 : 0;

    update(record.id, { status: newStatus })
      .then(() => {
        record.status = newStatus;
        createMessage.success(`[${record.name}] 状态修改成功`);
      })
      .catch(() => {
        createMessage.error(`[${record.name}] 状态修改失败`);
      })
      .finally(() => {
        record.pendingStatus = false;
      });
  }
</script>
